package com.push.common.downloader;

import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @类名 FileDownLoader
 * @描述 TODO
 * @作者 wang yanxi
 * @版本 1.0
 * @日期 2021-8-9 15:17
 */
public class FileDownLoader {
    public static int download(String soureUrl, String targetDir) throws IOException {
        int totalBytesRead = 0;
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(soureUrl);
        try {
            long startTime = System.currentTimeMillis();
            HttpResponse httpResponse = httpClient.execute(httpGet);
            StatusLine statusLine = httpResponse.getStatusLine();
            if (statusLine.getStatusCode() == 200) {
                File file = new File(targetDir);
                //如果路径不存在，则创建路径
                if (!file.getParentFile().exists()) {
                    boolean result = file.getParentFile().mkdirs();
                    if (!result) {
                        System.out.println("创建失败");
                    }
                }
                FileOutputStream writer = new FileOutputStream(file);
                InputStream reader = httpResponse.getEntity().getContent();
                byte[] buffer = new byte[153600];
                int bytesRead = 0;
                while ((bytesRead = reader.read(buffer)) > 0) {
                    writer.write(buffer, 0, bytesRead);
                    buffer = new byte[153600];
                    totalBytesRead += bytesRead;
                }
                long endTime = System.currentTimeMillis();
                writer.flush();
                writer.close();
                reader.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return totalBytesRead;
        } catch (IOException e) {
            e.printStackTrace();
            return totalBytesRead;
        } finally {
            httpGet.releaseConnection();
            httpClient.close();
        }
        return totalBytesRead;
    }

    /**
     * @描述 格式化输出
     * @参数 [second]
     * @返回 java.lang.String
     * @作者 wang yanxi
     **/
    private static String formatDisplay(int bits) {
        if(bits<1024){
            return bits+" bytes";
        }else if(bits<1024*1024) {
            return bits/1024+" kbytes";
        }else {
            return bits/(1024 * 1024)+" MB";
        }
    }
}
